<template>
  <div class="progress-form-container">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      class="progress-form"
    >
      <el-form-item label="事件类型" prop="event_type">
        <el-select v-model="formData.event_type" placeholder="请选择事件类型">
          <el-option :value="1" label="通知" />
          <el-option :value="2" label="进展" />
          <el-option :value="3" label="庭审" />
          <el-option :value="4" label="文书" />
          <el-option :value="5" label="任务" />
          <el-option :value="6" label="立案" />
          <el-option :value="7" label="提交材料" />
          <el-option :value="8" label="开庭" />
          <el-option :value="9" label="判决" />
          <el-option :value="10" label="执行" />
          <el-option :value="11" label="结案" />
          <el-option :value="12" label="其他" />
        </el-select>
      </el-form-item>

      <el-form-item label="事件日期" prop="event_time">
        <el-date-picker
          v-model="formData.event_time"
          type="date"
          placeholder="选择事件日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="事件内容" prop="content">
        <el-input
          v-model="formData.content"
          type="textarea"
          :rows="4"
          placeholder="请输入事件内容"
        />
      </el-form-item>

      <!-- 移除内部按钮，由外部对话框统一控制 -->
    </el-form>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import request from '@/utils/request'

  // 定义Props接口
  interface Props {
    isEdit?: boolean
    caseId?: number
    progressData?: any
  }

  // 定义Emits接口
  const emit = defineEmits(['success', 'cancel'])

  // 定义Props
  const props = withDefaults(defineProps<Props>(), {
    isEdit: false,
    caseId: 0,
    progressData: () => ({}),
  })

  // 表单引用
  const formRef = ref<FormInstance>()

  // 获取当前日期，格式化为yyyy-MM-dd
  const getCurrentDate = () => {
    const date = new Date()
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')

    return `${year}-${month}-${day}`
  }

  // 表单数据
  const formData = reactive({
    id: 0,
    case_id: props.caseId,
    event_type: 2, // 默认为进展
    event_time: getCurrentDate(),
    content: '',
  })

  // 表单验证规则
  const rules = reactive<FormRules>({
    event_type: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
    event_time: [{ required: true, message: '请选择事件时间', trigger: 'change' }],
    content: [
      { required: true, message: '请输入事件内容', trigger: 'blur' },
      { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' },
    ],
  })

  // 初始化
  onMounted(() => {
    // 确保初始时设置正确的caseId
    formData.case_id = props.caseId

    if (props.isEdit && props.progressData) {
      // 编辑模式，填充表单数据
      formData.id = props.progressData.id || 0
      formData.event_type = props.progressData.event_type || 2
      formData.event_time = props.progressData.event_time || getCurrentDate()
      formData.content = props.progressData.content || ''
    }
  })

  // 监听caseId变化，确保切换案件时更新表单中的case_id
  watch(
    () => props.caseId,
    newCaseId => {
      formData.case_id = newCaseId
    },
    { immediate: true }
  )

  // 提交表单
  const submitForm = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid, fields) => {
      if (valid) {
        try {
          // 根据模式选择API
          const apiUrl = props.isEdit
            ? '/api/lawcase/progresses/edit'
            : '/api/lawcase/progresses/add'

          const response: any = await request({
            url: apiUrl,
            method: props.isEdit ? 'put' : 'post',
            data: formData,
          })

          if (response.code === 0) {
            ElMessage.success(props.isEdit ? '编辑成功' : '添加成功')
            emit('success')
          } else {
            ElMessage.error(response.msg || (props.isEdit ? '编辑失败' : '添加失败'))
          }
        } catch (error) {
          ElMessage.error(props.isEdit ? '编辑失败，请重试' : '添加失败，请重试')
        }
      } else {
      }
    })
  }

  // 重置表单
  const resetForm = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
  }

  // 暴露方法给父组件
  defineExpose({
    submitForm,
    resetForm,
  })
</script>

<style scoped>
  .progress-form-container {
    padding: 20px 0;
  }

  .progress-form {
    max-width: 600px;
  }
</style>
